const Redis = require('ioredis');
const moment = require('moment');

module.exports = class Class {
  constructor (url) {
    this.redis = new Redis(url);
  }

  async getRedisLiveTime (room) {
    const today = moment().format('YYMMDD');
    const redisKey = 'live:' + room.platform.id + ':' + today + ':' +
      room.anchor.room;

    //读取redis缓存，拿出
    let lastTimestamp = await this.redis.get(redisKey);

    const now = Date.now();

    room.data.num_live = 0;

    if (lastTimestamp) {
      room.data.num_live = Math.floor((now - parseInt(lastTimestamp)) / 6e4);
    }

    //保存缓存，10分钟过期
    this.redis.set(redisKey, now, 'EX', 20 * 60);
  }

  hget (key, field) {
    return this.redis.hget(key, field);
  }

  hset (key, field, value) {
    return this.redis.hset(key, field, value);
  }

  async get (key, defaultValue) {
    const value = await this.redis.get(key);
    if (value)
      return value;
    return defaultValue;
  }

  set (key, value, expire) {
    if (expire > 0)
      return this.redis.set(key, value, 'EX', expire);
    return this.redis.set(key, value);
  }

  /** 设置过期 */
  expire (key, seconds) {
    return this.redis.expire(key, seconds);
  }

};